package com.veo.controller;

import com.veo.bean.Account;
import com.veo.exception.CustomException;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Controller
public class HelloController {

    @RequestMapping("/hello")
    public String hello() throws CustomException {
        throw new CustomException("参数异常");
    }


    @RequestMapping("/request")
    public String request(){
        return "forward:/pages/request.jsp";
    }

    @RequestMapping("/response")
    public String response(){
        return "redirect:/pages/response.jsp";
    }


    @RequestMapping("/responseBody")
    public @ResponseBody Account responseBody(){
        return new Account(1,"詹三",2000);
    }


    @RequestMapping("/uploadFile")
    public String uploadFile(String pname, MultipartFile uploadFile, HttpServletRequest request) throws IOException {
        System.out.println(pname + uploadFile);
        String fileName = "";
        String uploadedFileName = uploadFile.getOriginalFilename();
        String extendName = uploadedFileName.substring(uploadedFileName.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString().replace("-","").toUpperCase();
        if (StringUtils.hasLength(pname)){
            fileName = uuid + "_" + pname + extendName;
        }else {
            fileName = uuid + "_" + extendName;
        }
        System.out.println(fileName);

        String basePath = request.getServletContext().getRealPath("/uploads");
        String datePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        File file = new File(basePath + "/" + datePath);
        if (!file.exists()){
            file.mkdirs();
        }

        uploadFile.transferTo(new File(file,fileName));
        System.out.println("success");
        return "success";
    }
}
